<template>
	<view class="vercode-count-down">
		<slot></slot>
	</view>
</template>

<script>
	export default {
		name:"vercode-count-down",
		props: {
			value: {
				type: Number,
				default: 0
			}
		},
		data() {
			return {
				_countdownTime: 0,
				_timer: undefined,
			};
		},
		unmounted() {
			if(this._timer) {
				clearTimeout(this._timer)
			}
		},
		methods: {
			start: function() {
				this._countdownTime = this.value
				this.$emit("start", this.getValue())
				this.counting()
			},
			counting() {
				if(this._timer) {
					clearTimeout(this._timer)
				}
				if(this._countdownTime <= 0) {
					this.$emit("end", {})
					return
				}
				this._timer = setTimeout(() => {
					this._countdownTime -= 1000
					this.update()
					this.counting()
				}, 1000)
			},
			getValue: function() {
				let _timestamp = this._countdownTime
				let value = parseInt(_timestamp / 1000)
				
				let event = {}
				event["detail"] = {
				  value
				}
				return event
			},
			update: function() {
			  this.$emit("update", this.getValue())
			},
			
			checkTime: function(num) { //将0-9的数字前面加上0，例1变为01 
			  if(num<10) 
			  { 
				num = "0" + num; 
			  }
			  return num; 
			}
		}
	}
</script>

<style scoped>
	.vercode-count-down {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: center;
	}
</style>